<template>
	<view class="page">
		<view class="segment_wrap">
			<view class="segment">
				<view class="selector" @click="showDocType = true;">
					<!-- <view class="select-text" :style="{color: highlight}">{{showSexTitle==""?"性别":showSexTitle}}</view> -->
					<view>{{showDocTypeTitle}}</view>
					<view class="icon">
						<u-icon name="arrow-down-fill" :color="highlight" size="12"></u-icon>
					</view>
				</view>
				<view class="selector" @click="showDocTime = true;">
					<!-- <view class="select-text" :style="{color: highlight1}">{{showAgeTitle==""?"年龄":showAgeTitle}}</view> -->
					<view>{{showDocTimeTitle}}</view>
					<view class="icon">
						<u-icon name="arrow-down-fill" :color="highlight1" size="12"></u-icon>
					</view>
				</view>
			</view>
		</view>


		<view class="content">
			<u-index-list :index-list="data.map(item => item.code)" activeColor="#58C866">
				<u-checkbox-group v-model="slChilds" placement="column" :iconSize="21">
					<template v-for="(item, index) in data">
						<!-- #ifdef APP-NVUE -->
						<u-index-anchor :text="data.map(item => item.code)[index]" bgColor="#F5F6FA"
							height="30"></u-index-anchor>
						<!-- #endif -->
						<u-index-item>
							<!-- #ifndef APP-NVUE -->
							<!-- <u-index-anchor :text="indexList[index]"></u-index-anchor> -->
							<!-- #endif -->
							<!-- 		<view class="list-cell" v-for="(cell, index) in item">
							{{cell}}
						</view> -->
							<view v-for="(cell, row) in item.list">
								<rf-mdocCell :icon="cell.headSculpture" :childName="cell.childName" :name="cell.childId"
									:items="cell.docObjList">
									<u-checkbox activeColor="#58C866" :name="cell.childId" :key="row"
										@change="handleChange(cell.childId)"></u-checkbox></rf-mdocCell>
							</view>
						</u-index-item>
					</template>
				</u-checkbox-group>
			</u-index-list>
		</view>

		<!-- 页脚 -->
		<view class="footer">
			<view class="container">
				<u-checkbox-group placement="column" :iconSize="21">
					<u-checkbox activeColor="#58C866" :checked="isallcheck" @change="checkboxChange"
						label="全选"></u-checkbox>
				</u-checkbox-group>
				<view class="btn bg" @click="onClicked">下载</view>
			</view>
		</view>
		<!-- 选择文档类型 -->
		<view class="popup">
			<u-picker :show="showDocType" :columns="docTypes" keyName="name" title="文档类别" cancelColor="#3A3D4B"
				confirmColor="#58C866" @confirm="docTypeSelect" @cancel="showDocType = false"></u-picker>
		</view>

		<view class="popup">
			<!-- 选择评价的学期时间 -->
			<u-popup :show="showDocTime" :safeAreaInsetBottom="false" :round="10" mode="bottom">
				<view style="height: 80rpx; position: relative;">
					<view
						style="display: flex;justify-content: center;align-items: center;height: 80rpx;font: bold;letter-spacing: 3rpx;">
						时间范围
					</view>
					<view style="color: #58c866; position: absolute;right: 30rpx;top: 30rpx;" @click="onClickedDocTime">
						不限时间
					</view>
				</view>
				<view style="display: flex;width: 100%;">
					<view style="width: 100%; ">
						<picker-view indicator-style="height: 50px;" v-model="dayday" @change="bindStartDate"
							class="picker-view">
							<picker-view-column>
								<view class="item" v-for="(item,index) in years" :key="index">{{item}}</view>
							</picker-view-column>
							<picker-view-column>
								<view class="item" v-for="(item,index) in months" :key="index">{{item}}</view>
							</picker-view-column>
						</picker-view>
					</view>
					<view style="display: flex; justify-content: center; align-items: center; margin: 0rpx 30rpx;">至
					</view>
					<view style="width: 100%;">
						<picker-view indicator-style="height: 50px;" :value="value" @change="bindEndDate"
							class="picker-view">
							<picker-view-column>
								<view class="item" v-for="(item,index) in years" :key="index">{{item}}</view>
							</picker-view-column>
							<picker-view-column>
								<view class="item" v-for="(item,index) in months" :key="index">{{item}}</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
				<view class="picker-btn">
					<view class="btn" @click="showDocTime = false">取消</view>
					<view class="btn confirm" @click="pickerChange">确定</view>
				</view>
			</u-popup>
		</view>
		<!-- load -->
		<rf-load :loading="loading"></rf-load>
		<!-- 下载复制 -->
		<rf-downloadTips :show="downloadTipsShow" :desc="downloadUrl"
			@confirm="downloadTipsShow = false"></rf-downloadTips>
		<rf-toast :show="toastShow" @click="toastShow = false" :isSus="false" des="请选择开始与结束时间"></rf-toast>

	</view>
</template>

<script>
	import {
		getMyDocList,
		downloadDoc,
	} from "@/api/user.js"

	export default {
		data() {
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const day = date.getDate()
			for (let i = 1990; i <= date.getFullYear(); i++) {
				years.push(i)
			}
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}

			return {

				years,
				months,
				days,

				year,
				month,
				day,

				value: [years.length, month - 1, day - 1], // 设置默认值，分别是年的索引，月的索引，日的索引
				dayday: [years.length, month - 1], // 设置默认值，分别是年的索引，月的索引，日的索引


				showDocType: false, // 选择文档类型
				showDocTypeTitle: "文档类别",

				docTypes: [
					[{
						'name': '全部',
						'value': "0",
					}, {
						'name': '观察记录',
						'value': "1",
					}, {
						'name': '学期评价',
						'value': "2",
					}]
				],

				showDocTime: false,
				showDocTimeTitle: "时间范围",

				params: {
					type: 0,
					startTime: "",
					endTime: "",
				},

				// 恢复默认时间
				startTime: "",
				endTime: "",

				data: [],
				// indexList: ["A", "B", "C"],


				isallcheck: false, // 是否全选
				checkboxValue1: [], // 所有被选择的文件ID
				slChilds: [], // 被选择的孩子ID

				loading: false,
				downloadTipsShow: false, // 显示下载链接
				downloadUrl: "", // 下载链接
				toastShow: false,
			}
		},
		computed: {
			indexList() {
				return new Array(26).fill("A").map((char, index) => String.fromCharCode(65 + index));
			}
		},
		watch: {

			downloadTipsShow(val) {
				if (val) {
					this.loading = false
				}
			},
			toastShow(val) {
				if (val) {
					this.loading = false
					this.showDocType = false
					this.showDocTime = false
				}
			}
		},
		onLoad() {

			this.getdocList()

			// this.params.startTime = ""
			// this.params.endTime = ""
		},
		methods: {
			getdocList() {
				this.loading = true
				getMyDocList(this.params).then(res => {
					this.loading = false
					this.data = res.data;
					console.log("res----------------" + JSON.stringify(res));
				}).catch(err => {

				})
			},
			onClickedDocTime() {
				this.startTime = this.params.startTime;
				this.endTime = this.params.endTime;

				// 不限时间范围
				this.params.startTime = "";
				this.params.endTime = "";
				this.showDocTimeTitle = "不限时间";
				this.showDocTime = false;

				this.getdocList()
				// 重新设置默认时间
				this.params.startTime = this.startTime
				this.params.endTime = this.endTime
			},
			docTypeSelect(e) {
				this.showDocType = false;
				this.showDocTypeTitle = e.value[0].name;
				this.params.type = e.value[0].value;
				this.getdocList()
				// 根据选择年龄，重新设置 生日默认值
				// const currentDate = new Date();
				// const previousMonth = new Date(currentDate.getTime() - (this.form.childAge * 365 * 24 * 60 * 60 *
				// 	1000));
				// const timeFormat = uni.$u.timeFormat;
				// let timeValue = timeFormat(previousMonth, 'yyyy-mm-dd');
				// this.form.beBornDt = timeValue
			},

			pickerChange() {
				console.log(this.value);
				console.log(this.dayday);
				var date = new Date()
				if (this.params.startTime.length <= 0) {
					this.params.startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-01"
					this.startTime = date.getFullYear() + "-" + (date.getMonth() + 1)
				}
				if (this.params.endTime.length <= 0) {
					this.params.endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-31"
					this.endTime = date.getFullYear() + "-" + (date.getMonth() + 1)
				}
				// this.params.startTime = this.year + "-" + this.month
				// this.params.endTime = this.year + "-" + this.month
				this.showDocTimeTitle = this.startTime + "至" + this.endTime

				this.showDocTime = false;
				this.getdocList()
				// this.startAndendDate = this.form.startTime + "至" + this.form.endTime
			},
			bindStartDate: function(e) {

				const val = e.detail.value
				this.year = this.years[val[0]]
				this.month = this.months[val[1]]
				// this.day = this.days[val[2]]
				// this.params.startTime = this.year + "-" + this.month + "-" + this.day
				this.params.startTime = this.year + "-" + this.month + "-01"
				this.startTime = this.year + "-" + this.month

			},
			bindEndDate: function(e) {

				const val = e.detail.value

				this.year = this.years[val[0]]
				this.month = this.months[val[1]]
				// this.day = this.days[val[2]]
				this.params.endTime = this.year + "-" + this.month + "-31"
				this.endTime = this.year + "-" + this.month
			},
			handleChange(val) {
				let that = this;
				// val 孩子ID
				console.log(JSON.stringify(val));
				var index = this.slChilds.indexOf(val);
				if (index !== -1) {
					// 存在
					this.slChilds.splice(index, 1);
				} else {
					// 不存在
					this.slChilds.push(val);
				}

				this.checkboxValue1.length = 0
				this.data.forEach(item => {

					this.slChilds.forEach(childId => {
						item.list.forEach(obj => {
							if (obj.childId === Number(childId)) {
								obj.docObjList.forEach(doc => {
									that.checkboxValue1.push(doc.id);
								});
							}
						});
					});
				});

			},
			checkboxChange() {
				this.isallcheck = !this.isallcheck;

				if (this.isallcheck) {
					this.data.forEach(item => {
						item.list.forEach(obj => {
							obj.docObjList.forEach(doc => {
								this.checkboxValue1.push(doc.id);
							});
						});
					});

					this.checkboxValue1 = [...new Set(this.checkboxValue1)];

					this.data.forEach(item => {
						item.list.forEach(obj => {
							this.slChilds.push(obj.childId);
						});
					});

					this.slChilds = [...new Set(this.slChilds)];
				} else {
					this.checkboxValue1.length = 0
					this.slChilds.length = 0
				}
			},
			onClicked() {
				// 下载
				console.log("this.checkboxChange1: " + JSON.stringify(this.checkboxValue1));
				if (this.slChilds.length <= 0) {
					return
				}

				this.loading = true;
				this.params["childList"] = this.slChilds

				var param = {}
				param["childList"] = this.slChilds
				param["type"] = this.params.type
				param["startTime"] = this.params.startTime
				param["endTime"] = this.params.endTime
				// console.log("-----------------" + JSON.stringify(param));

				downloadDoc(param).then(res => {
					this.loading = false;
					this.downloadUrl = res.data
					this.downloadTipsShow = true
					console.log(JSON.stringify(res));
				}).catch(err => {
					this.loading = false;
				})

			},
			// 下载文件
			oneClickDownload(url) {


				// 下载文件资源到本地
				uni.downloadFile({
					url: url, // 后端返回的线上文件路径
					success: function(res) {
						console.log(JSON.stringify(res));
						if (res.statusCode === 200) {
							// 文件到本地
							uni.saveFile({
								tempFilePath: res.tempFilePath, //临时路径
								success: function(data) {
									console.log(JSON.stringify(data));
									var savedFilePath = data.savedFilePath
									// 在app端执行

									// #ifdef APP-PLUS
									let osname = plus.os.name
									// 如果是安卓的话弹出提示
									if (osname == 'Android') {
										uni.showToast({
											icon: 'none',
											mask: true,
											title: '保存成功',
											duration: 1000
										})
									}
									// #endif
									//ios手机直接打开文件，手动存储文件到手机，Android手机从根目录创建文件夹，保存文件并改名
									setTimeout(() => {
										//打开文档查看
										uni.openDocument({
											filePath: data.savedFilePath,
											success: function(ress) {
												console.log("成功打开文件")
											},
											fail() {
												console.log("打开文件失败")
											}
										})
									}, 1000)
								}
							})
							console.log('下载成功');
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					},
					complete: function(res) {
						console.log(res.statusCode);
					},
					progress: function(res) {
						console.log('下载进度' + res.progress);
					}
				});
			}

		}
	}
</script>

<style lang="scss">
	.page {
		background-color: #fff;
		height: 100%;
		overflow-y: scroll;
		-webkit-overflow-scrolling: touch;
	}

	.segment_wrap {
		height: 76rpx;
		position: relative;

		.segment {
			width: 100%;
			height: 76rpx;
			background-color: white;
			display: flex;
			// color: green;
			position: fixed;
			// top: 96rpx;
			z-index: 999;


			.selector {
				display: flex;
				justify-content: center;
				align-items: center;
				flex: 1;

				.icon {
					margin-left: 10rpx;
				}
			}

		}
	}

	.content {
		margin-bottom: 180rpx;

	}


	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 14px;
		line-height: 24px;
		background-color: #fff;
	}

	.footer {
		position: fixed;
		z-index: 999;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 180rpx;
		background: #fff;
		box-shadow: 0rpx -4rpx 8rpx 0rpx rgba(0, 0, 0, 0.02), 0rpx -1rpx 0rpx 0rpx rgba(0, 0, 0, 0.02);


		.container {
			top: 0rpx;
			height: 112rpx;
			padding: 0rpx 32rpx;
			display: flex;
			align-items: center;

			.btn {
				margin-left: 28rpx;
				width: 94%;
				height: 88rpx;
				border-radius: 44rpx;
				font-size: 32rpx;
				font-weight: 600;
				line-height: 88rpx;
				text-align: center;
				border: 1rpx solid #58c866;
				color: #FFF;
				background: #58c866;
			}
		}
	}

	.popup {
		// position: relative;

		.u-popup__content {
			// position: relative;
			border-radius: 24rpx 24rpx 0 0;
			// overflow: hidden;
			padding-bottom: 100rpx;

		}

		// .u-picker__view {
		// 	height: 360rpx !important;
		// }


		.u-toolbar__wrapper__cancel {
			padding: 0;
			position: absolute;
			left: 100rpx;
			bottom: -78rpx;

			width: 200rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.u-toolbar__wrapper__confirm {
			padding: 0;
			position: absolute;
			right: 100rpx;
			bottom: -78rpx;

			width: 200rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}



	.picker-view {
		width: 100%;
		height: 400rpx;
		margin-top: 20rpx;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	.picker-btn {
		display: flex;
		margin-top: 40rpx;
		margin-bottom: 40rpx;

		.btn {
			flex: 1;
			width: 200rpx;
			height: 72rpx;
			// color: #58C866;
			// background: #FFFFFF;
			// border-radius: 36rpx;
			// border: 2rpx solid #58C866;
			text-align: center;
			line-height: 72rpx;
			margin: 0 10rpx;
		}

		.confirm {
			color: #58C866;
			// color: #fff;
		}
	}
</style>